const domain = getApp().globalData.domain
Page({
  data: {
    organization: {
      deptId: 0,
      deptName: "广师大科教",
      logo: '/image/test.png',
      description: "“广东技术师范大学科教中心”（简称：广师大科教）是我校校级学生组织，是在校党委宣传部的直接指导帮助下，由教育科学...",
      orderNum: 798,
      identity: '校级组织',
      award: '荣誉...别说我还真不知道',
      devhistory: '历史还挺悠久的，就是没有找到记录',
      album: [{
          url: '/image/testImg/photo.png',
          type: 'img'
        },
        {
          url: '/image/testImg/photo.png',
          type: 'img'
        },
      ]
    },
    chosenFile: undefined,
    // chosenFile: {
    //   fileName: '吴颖浩-网络研发部.pdf',
    //   fileType: 'pdf'
    // },
    showText: '',
    highLightItem: 0,
    activityContent: [],
    activityTitle: [],
    chosenIndex: undefined,
    deletion: {
      will: false,
      file: false
    }
  },
  async onLoad(option) {
    const that = this
    //获取deptId
    const deptId = parseInt(option.deptId)
    //获取组织信息
    const deptInfo = await getApp().getDeptInfo(deptId)
    const formatInfo = await this.formatDeptInfo(deptInfo)
    //渲染组织信息并初始化组织介绍内容
    console.log('组织信息', formatInfo)
    this.setData({
      organization: formatInfo,
      showText: formatInfo.organizationVO.description
    })
    //获取已开始的活动内容
    const actObject = await this.getActivityInfo(deptId)
    this.setData({
      activityTitle: actObject.currentActTitle,
      activityContent: actObject.currentAct
    })
    //获取组织总投递数
    const deliverNum = await this.getHot()
    this.setData({
      'organization.deliverNum': deliverNum
    })
  },
  /*
  给未填的信息打高光
  参数1:高光项目(will,file,all)
  参数2:打不打高光
  */
  glowing(view, empty) {
    const origin = this.data.deletion
    const deletion = {
      will: (view == 'will' || view == 'all') ? empty : origin.will,
      file: (view == 'file' || view == 'all') ? empty : origin.file
    }
    console.log(deletion)
    this.setData({
      deletion: deletion
    })
  },
  //获取组织总投递数
  getHot() {
    const that = this
    //获取当前时间
    const now = new Date()
    //投递
    return new Promise((resolve, reject) => {
      wx.request({
        url: domain + '/api/activity/listByOrgId',
        method: "GET",
        data: {
          orgId: that.data.organization.organizationVO.id,
          status: 1,
          year: now.getFullYear()
        },
        header: {
          "content-type": "application/x-www-form-urlencoded",
          "token": wx.getStorageSync('token')
        },
        success: res => {
          // console.log(res.data)
          if (res.data.code === 50000) { //系统错误
            reject(0)
            getApp().showMessage('系统错误，请稍后重试！')
            return
          } else if(res.data.code === 40000){ //活动不在允许的时间内
            reject(0)
            getApp().showMessage('活动不在允许的时间内')
            return;
          } else {
            const actData = res.data.data
            var deliverNum = 0
            //求所有活动投递数量的总和
            actData.forEach((item, index) => {
              deliverNum = deliverNum + item.deliverNum
            })
            //返回投递数
            resolve(deliverNum)
          }
        },
        fail: err => {
          console.error(err)
          reject(0)
        }
      })
    })
  },
  //确认投递
  confirmDeliver() {
    const that = this
    //确认是否选择意向和建立附件
    this.glowing('will', that.data.chosenIndex === undefined)
    this.glowing('file', that.data.chosenFile === undefined)
    if (that.data.chosenIndex === undefined || that.data.chosenFile === undefined) {
      getApp().showMessage('请填写完整信息！')
      return
    }
    //获取活动Id
    const activityID = that.data.activityContent[0].id
    //开始投递
    console.log(that.data.chosenFile)
    getApp().showLoading('加载中...')
    wx.uploadFile({
      filePath: that.data.chosenFile.filePath,
      name: "file",
      url: domain + '/api/activityUser/uploadApplicationFormFile',
      formData: {
        activityID: activityID,
        openid: wx.getStorageSync('openId')
      },
      header:{
        "token":wx.getStorageSync('token')
      },
      success: (res) => {
        console.log(JSON.parse(res.data))
        const resData = JSON.parse(res.data)
        if (resData.code === 50000) { //系统错误
          reject(0)
          getApp().showMessage('系统错误，请稍后重试！')
          return
        } else if(resData.code === 40000){ //活动不在允许的时间内
          reject(0)
          getApp().showMessage('活动不在允许的时间内')
          return;
        }
        getApp().showMessage('投递成功！')
        setTimeout(() => {
          wx.navigateBack()
        }, 2000)
      },
      fail(err) {
        console.error(err)
        getApp().showMessage('投递失败！')
      }
    })
  },
  //点击上传附件
  chooseFile() {
    const that = this
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      success(res) {
        var fileInfo = res.tempFiles[0]
        //获取文件类型
        const fileType = that.getFileFormat(fileInfo.name)
        //其他类型文件提示
        if (fileType != 'docx' && fileType != 'doc' && fileType != 'pdf') {
          getApp().showMessage('请上传Word或PDF文件！')
          return
        }
        //文件名长度限制
        fileInfo.name = that.truncateString(fileInfo.name, 35)
        //上传文件
        that.setData({
          chosenFile: {
            fileName: fileInfo.name,
            fileType: fileType,
            filePath: fileInfo.path,
            iconPath: `/image/fileType/${fileType}.png`
          }
        })
      },
      fail(err) {
        console.error(err)
        getApp().showMessage('上传文件失败！')
      }
    })
  },
  //获取文件扩展名
  getFileFormat(fileName) {
    // 检查输入是否为字符串
    if (typeof fileName !== 'string') {
      return '输入无效，必须是字符串';
    }
    // 使用正则表达式检查是否有扩展名
    const match = fileName.match(/\.[^.]+$/);
    if (match) {
      // 返回去掉点号的扩展名
      return match[0].slice(1).toLowerCase();
    } else {
      return '无扩展名';
    }
  },
  //限制文件名长度
  truncateString(str, maxLength) {
    // 检查输入是否有效
    if (typeof str !== 'string' || typeof maxLength !== 'number' || maxLength <= 0) {
      return '输入无效';
    }

    // 如果字符串长度小于或等于最大长度，则无需截断
    if (str.length <= maxLength) {
      return str;
    }

    // 截断字符串，并在末尾加上省略号
    return str.slice(0, maxLength - 3) + '...';
  },
  //选择器选择后
  pickIntention(e) {
    const index = parseInt(e.detail.value)
    this.setData({
      chosenIndex: index
    })
  },
  //获取活动列表
  async getActivityInfo(deptId) {
    const allAcitvities = await getApp().getActivityInfo();
    var currentAct = []
    var currentActTitle = []
    allAcitvities.forEach((item, index) => {
      //推入部门ID相同，已开始的活动
      if (item.deptId == deptId && item.status % 2 != 0) {
        currentActTitle.push(item.title)
        currentAct.push(item)
      }
    })
    return {
      currentActTitle: currentActTitle,
      currentAct: currentAct
    };
  },
  //格式化获取的信息
  async formatDeptInfo(deptInfo) {
    //整理组织信息
    const organizationVO = deptInfo.organizationVO
    //leader姓名和url不可用则显示默认内容
    if (organizationVO.leader.userName == "") {
      deptInfo.organizationVO.leader.userName = "userName"
    }
    console.log(organizationVO.leader.userAvatar)
    if (this.checkFileType(organizationVO.leader.userAvatar) !== 'image') {
      deptInfo.organizationVO.leader.userAvatar = '/image/testImg/avatar_notWolf.png'
    }
    //检查组织相册中的内容是否合规
    const that = this
    const originAlbum = organizationVO.photoAlbum
    originAlbum.forEach(async (item, index) => {
      const type = that.checkFileType(item)
      deptInfo.organizationVO.photoAlbum[index] = {
        id: index,
        url: item,
        fileType: type
      }
    })
    //最后返回修改好的内容
    return deptInfo;
  },
  //改变展示内容
  changeShow(e) {
    const index = parseInt(e.currentTarget.dataset.index)
    var text;
    const organVO = this.data.organization.organizationVO
    // 设置文本内容
    switch (index) {
      case 0:
        text = organVO.description
        break;
      case 1:
        text = organVO.honors
        break;
      case 2:
        text = organVO.devHistory
        break;
    }
    //渲染文本内容和高光元素
    this.setData({
      showText: text,
      highLightItem: index
    })
  },
  //判断字符串是不是可用的图片视频地址(需要扩展名)
  checkFileType(filePath) {
    // 定义支持的图片和视频扩展名
    const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'tiff'];
    const videoExtensions = ['mp4', 'mkv', 'webm'];
    // 获取文件的扩展名
    const extension = filePath.split('.').pop().toLowerCase();
    if (imageExtensions.includes(extension)) {
      return 'image';
    } else if (videoExtensions.includes(extension)) {
      return 'video';
    } else {
      return 'unknown';
    }
  },
  //视频渲染出错
  videoError(e) {
    console.log(e.detail.errMsg)
    const errorIndex = e.currentTarget.dataset.index
    const organInfo = this.data.organization
    //去掉出问题的视频
    organInfo.organizationVO.photoAlbum[errorIndex].fileType = 'error'
    this.setData({
      organization: organInfo
    })
  }
})